package com.qyhl.webtv.commonlib.utils.coin;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;

import com.qyhl.webtv.commonlib.R;


public class GoldCoinTimeView extends View {
    /**
     * 控件宽高
     */
    private int size;
    /**
     * 外围宽度
     */
    private int division = 15;

    /**
     * 图片画笔
     */
    private Paint imgPaint;

    /**
     * 圆弧画笔
     */
    private Paint divisionPaint;
    /**
     * 图片
     */
    private Bitmap bitmap;
    /**
     * 进度倍率
     */
    private int multiplerate = 20;
    /**
     * 进度*20
     */
    private int progress = 0 * multiplerate;
    /**
     * 总进度(一圈的时间)*20
     */
    private int maxProgress = 20 * multiplerate;

    /**
     * 变换标志
     */
    private boolean istransformation = false;
    /**
     * 变换数
     */
    private String transformationText;
    /**
     * 变换图片
     */
    private Bitmap transformationbitmap;
    /**
     * 字体偏移量
     */
    private float textOffset;
    /**
     * 秒计时器Handler
     */
    private Handler secondhandler;

    /**
     * 计时器Handler
     */
    private Handler handler;
    /**
     * 计时器Runnable
     */
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isStartTime) {
                if (!isRepeat) {
                    timekeep--;
                }
                if (timekeep > 0) {
                    handler.postDelayed(this, 1000 / multiplerate);
                } else {
                    isStartTime = false;
                }
                progress++;
                invalidate();
                if (progress >= maxProgress) {
                    progress = 0;
                    listener.timeout();
                    numLimit--;
                    if (numLimit == 0) {
                        limitStatus = false;
                        listener.limit();
                    }
                }
            }
        }
    };
    /**
     * 时间累积计数
     */
    private int timekeep;
    /**
     * 计时标志
     */
    private boolean isStartTime = false;
    /**
     * 圈数上限 小于0无限
     */
    private int numLimit = 3;
    /**
     * 圈数上限标志,true表示可以开始
     */
    private boolean limitStatus = true;

    /**
     * 控制无限跑圈
     */
    private boolean isRepeat = false;
    /**
     * 禁止跑圈
     */
    private boolean enjoin = false;

    public void setRepeat(boolean repeat) {
        isRepeat = repeat;
    }

    /**
     * 一圈到达的监听器
     */
    private OnTimeoutListener listener;

    public GoldCoinTimeView(Context context) {
        this(context, null);
    }

    public GoldCoinTimeView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GoldCoinTimeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        imgPaint = new Paint();
        imgPaint.setStyle(Paint.Style.FILL);
        imgPaint.setAntiAlias(true);
        imgPaint.setColor(ContextCompat.getColor(getContext(), R.color.global_base));
        imgPaint.setTextAlign(Paint.Align.LEFT);

        bitmap = BitmapFactory.decodeResource(this.getContext().getResources(),
                R.drawable.coin_get_icon);

        transformationbitmap = BitmapFactory.decodeResource(this.getContext().getResources(),
                R.drawable.coin_get_icon2);

        divisionPaint = new Paint();
        divisionPaint.setStyle(Paint.Style.STROKE);
        divisionPaint.setStrokeWidth(division);
        divisionPaint.setAntiAlias(true);
        divisionPaint.setStrokeCap(Paint.Cap.ROUND);

        handler = new Handler(Looper.getMainLooper());
        secondhandler = new Handler(Looper.getMainLooper());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthmode = MeasureSpec.getMode(widthMeasureSpec);
        int widtsize = MeasureSpec.getSize(widthMeasureSpec);
        if (widthmode != MeasureSpec.EXACTLY) {
            widtsize = 250;
        }

        int heightmode = MeasureSpec.getMode(heightMeasureSpec);
        int heightsize = MeasureSpec.getSize(heightMeasureSpec);
        if (heightmode != MeasureSpec.EXACTLY) {
            heightsize = 250;
        }
        //取最小值
        size = Math.min(heightsize, widtsize);
        setMeasuredDimension(size, size);
    }

    @SuppressLint("NewApi")
    @Override
    protected void onDraw(Canvas canvas) {
        if (istransformation) {
            //text总共绘制区域可用宽度   -两边分割线 -20边距 -图片宽度 -图片边距5
            float textWidth = (float) (size - division - 20) / 7 * 4 - 5;
            float imgWidth = (float) (size - division - 20) / 7 * 3;
            float imgHeight = imgWidth / transformationbitmap.getWidth() * transformationbitmap.getHeight();
            canvas.drawText(transformationText, division / 2 + 10, size / 2 - textOffset - 2, imgPaint);
            canvas.drawBitmap(transformationbitmap, null,
                    new RectF(division / 2 + 10 + textWidth + 5,
                            size / 2 - imgHeight / 2,
                            size - division / 2 - 10,
                            size / 2 + imgHeight / 2), null);
        } else {
            float drawHeight = (float) size / 2;
            float drawWidth = drawHeight * bitmap.getWidth() / bitmap.getHeight();
            canvas.drawBitmap(bitmap, null, new RectF(size / 2 - drawWidth / 2, size / 2 - drawHeight / 2,
                    size / 2 + drawWidth / 2, size / 2 + drawHeight / 2), null);
            divisionPaint.setColor(0xffE53935);

            if (enjoin) {
                //中心点到线段起始点xy距离
                float length = (float) ((size - division) / 2 / Math.sqrt(2));
                divisionPaint.setColor(0xffE53935);
                canvas.drawLine(size / 2 - length, size / 2 - length,
                        size / 2 + length, size / 2 + length, divisionPaint);
            }
        }
        divisionPaint.setColor(0xffE8E8E8);
        canvas.drawArc(division / 2, division / 2, size - division / 2, size - division / 2,
                -90, 360, false, divisionPaint);
        divisionPaint.setColor(0xffE53935);
        canvas.drawArc(division / 2, division / 2, size - division / 2, size - division / 2,
                -90, (float) progress / maxProgress * 360, false, divisionPaint);
    }

    public void beginTime() {
        enjoin = false;
        timekeep = maxProgress / 5;
        if (!isStartTime) {
            if (limitStatus) {
                isStartTime = true;
                handler.postDelayed(runnable, 1000 / multiplerate);
            }
        }
    }

    public void resetMin() {
        stopTime();
        progress = 0;
        invalidate();
    }

    public void resetMax() {
        stopTime();
        progress = maxProgress;
        invalidate();
    }

    public void stopTime() {
        isStartTime = false;
        handler.removeCallbacksAndMessages(null);
    }

    public void setProgress(int progress) {
        this.progress = progress * multiplerate;
        this.progress = Math.max(Math.min(this.progress, maxProgress), 0);
        invalidate();
    }

    public int getProgress() {
        return this.progress / multiplerate;
    }

    public void setMaxProgress(int maxProgress) {
        this.maxProgress = maxProgress * multiplerate;
    }

    public void setDivision(int division) {
        this.division = division;
        divisionPaint.setStrokeWidth(division);
        invalidate();
    }

    public void setNumLimit(int numLimit) {
        this.numLimit = numLimit;
    }

    public void setEnjoin(boolean enjoin) {
        this.enjoin = enjoin;
        invalidate();
    }

    //变换
    public void transformation(String transformationText, int delay) {
        if (!istransformation) {
            this.transformationText = "+" + transformationText;

            //text总共绘制区域可用宽度   -两边分割线 -20边距  占4份  -图片边距5
            float textWidth = (float) (size - division - 20) / 7 * 4 - 5;
            //计算文字大小
            int textsize = 25;
            imgPaint.setTextSize(textsize);
            while (imgPaint.measureText(this.transformationText) < textWidth) {
                textsize++;
                imgPaint.setTextSize(textsize);
            }
            Paint.FontMetrics fontMetrics = imgPaint.getFontMetrics();
            textOffset = fontMetrics.top / 2 + fontMetrics.bottom / 2;

            istransformation = true;
            secondhandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    istransformation = false;
                    invalidate();
                }
            }, delay * 1000);
            invalidate();
        }
    }

    public void setOnTimeoutListener(OnTimeoutListener listener) {
        this.listener = listener;
    }

    public interface OnTimeoutListener {
        /**
         * 达到一圈回调
         */
        void timeout();

        /**
         * 圈数达到上限回调
         */
        void limit();
    }
}
